﻿using Abp.Collections.Extensions;
using IdentityServer4;
using IdentityServer4.Models;
using Microsoft.Extensions.Configuration;
using System.Collections.Generic;
using System.Linq;

namespace Hicap.AuthorizationServer.Core.IdentityServer
{
    public class Config
    {
        private readonly IConfiguration _configuration;

        public Config(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public static IEnumerable<IdentityResource> GetIdentityResourceResources()
        {
            return new List<IdentityResource>
            {
                new IdentityResources.OpenId(), //必须要添加，否则报无效的scope错误
                new IdentityResources.Profile()
            };
        }

        // scopes define the API resources in your system
        public static IEnumerable<ApiResource> GetApiResources()
        {
            List<ApiResource> result = new List<ApiResource>();
            AuthorizationServerConsts.ApiResourceNameList.ForEach(x => result.Add(new ApiResource(x, x)));
            return result;
        }

        // clients want to access resources (aka scopes)
        public static IEnumerable<Client> GetClients()
        {
            Client allApplicationClient = new Client
            {
                ClientId = AuthorizationServerConsts.ApiResourceNameList.FirstOrDefault(),
                AllowedGrantTypes = GrantTypes.ResourceOwnerPassword
            };

            allApplicationClient.ClientSecrets.AddIfNotContains(new Secret(
           AuthorizationServerConsts.TokenSecurityKey.FirstOrDefault().Sha256()));
            allApplicationClient.AllowedScopes.AddIfNotContains(IdentityServerConstants.StandardScopes.OpenId);
            allApplicationClient.AllowedScopes.AddIfNotContains(IdentityServerConstants.StandardScopes.Profile);
            AuthorizationServerConsts.ApiResourceNameList.ForEach(x => allApplicationClient.AllowedScopes.AddIfNotContains(x));

            Client authorizationClient = new Client
            {
                ClientId = AuthorizationServerConsts.ApiResourceNameList.LastOrDefault(),
                AllowedGrantTypes = GrantTypes.ResourceOwnerPassword
            };

            authorizationClient.ClientSecrets.AddIfNotContains(new Secret(AuthorizationServerConsts.TokenSecurityKey.FirstOrDefault().Sha256()));
            authorizationClient.AllowedScopes.AddIfNotContains(IdentityServerConstants.StandardScopes.OpenId);
            authorizationClient.AllowedScopes.AddIfNotContains(IdentityServerConstants.StandardScopes.Profile);
            authorizationClient.AllowedScopes.AddIfNotContains(AuthorizationServerConsts.ApiResourceNameList.LastOrDefault());

            // client credentials client
            return new List<Client>
            {
                allApplicationClient,
                authorizationClient
            };
        }
    }
}